package top.maof.book.service.myImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.maof.book.dao.*;
import top.maof.book.model.BookInfo;
import top.maof.book.service.BookInfoService;

@Service
public class BookInfoServiceImpl extends ServiceImpl<BookInfoMapper, BookInfo> implements BookInfoService {

    @Autowired
    HistoryMapper historyMapper;

    @Autowired
    ShelfMapper shelfMapper;

    @Autowired
    LikesMapper likesMapper;

    @Autowired
    ScoreMapper scoreMapper;

    public boolean addForward(Integer bookId, int delta){
        BookInfo bookInfo = this.getByBookId(bookId);
        bookInfo.setForwardNum(bookInfo.getForwardNum() + delta);
        return this.updateById(bookInfo);
    }

    @Transactional
    @Override
    public void addLikes(Integer bookId, int delta) {
        BookInfo one = this.getByBookId(bookId);
        one.setLikesNum(one.getLikesNum() + delta);
        this.updateById(one);
    }

    @Transactional
    @Override
    public void addCollection(Integer bookId, int delta) {
        BookInfo one = this.getByBookId(bookId);
        one.setCollectionNum(one.getCollectionNum() + delta);
        this.updateById(one);
    }

    @Transactional
    @Override
    public void addClick(Integer bookId, int delta) {
        BookInfo one = this.getByBookId(bookId);
        one.setClickNum(one.getClickNum() + delta);
        this.updateById(one);
    }


    @Transactional
    @Override
    public BookInfo getByBookId(Integer bookId) {
        LambdaQueryWrapper<BookInfo> queryWrapper = Wrappers.<BookInfo>lambdaQuery();
        queryWrapper.eq(BookInfo::getBookId, bookId);
        BookInfo one = this.getOne(queryWrapper);
        if (one == null) {
            one = new BookInfo();
            one.setBookId(bookId);
            Integer click = historyMapper.clickCount(bookId);
            one.setClickNum(click == null ? 0 : click);
            Integer shelfNum = shelfMapper.shelfNum(bookId);
            one.setCollectionNum(shelfNum == null ? 0 : shelfNum);
            one.setForwardNum(0);
            Integer likesNum = likesMapper.likesNum(bookId);
            one.setLikesNum(likesNum == null ? 0 : likesNum);
            Double bookScore = scoreMapper.bookScore(bookId);
            one.setScore(bookScore == null ? 0 : bookScore);
            this.save(one);
        }
        return one;
    }
}
